<!--
 * @Description: 公共支付页面
 * @Author: Kerwin
 * @Date: 2025-05-27 11:17:15
 * @LastEditTime: 2025-05-27 11:22:06
 * @LastEditors:  Please set LastEditors
-->

<template>
    <view class="physicalShopCheck">
        <!-- 导航栏 -->
        <u-navbar back-text="" :title="'店铺付款'" :title-bold="true" :is-back="!enterByStoreQrcode"
            v-if="!isWeChatBrowser && !isAlipayClient" color="#333"></u-navbar>

        <!-- 头部 -->
        <view class="topTitLe">
            <view class="leftTitle">
                <view style="font-weight: 700;font-size: 32rpx;margin-bottom: 20rpx;">消费总金额</view>
                <view style="color: #999;">请询问金额后提交</view>
            </view>
            <view class="rightTitle">
                <u-image width="180rpx" height="150rpx" :src="moneyIcon"></u-image>
            </view>
        </view>

        <!-- 商户信息 -->
        <view class="shopBox">
            <text class="name"><u-icon size="40" style="vertical-align: middle;" :name="shopIcon1"></u-icon> {{
                info.name }}</text>

            <!-- 输入金额 -->
            <view class="inptBox">
                <u-input v-model="money" v-input-decimal type="digit" inputmode="decimal" focus pattern="number"
                    placeholder="¥ 0.00" input-align="center" :custom-style="{ fontSize: '52rpx' }"
                    :disabled="inptDisabled" />
                <text class="unit">(元)</text>
            </view>

            <!-- 积分抵扣区域（插槽） -->
            <slot name="score-deduction" />

            <!-- 支付规则选择 -->
            <view class="radioBox" v-if="info.shopMoneyRules && info.shopMoneyRules.length > 1">
                <u-radio-group v-model="moneyRuleId" @change="radioGroupChange" :wrap="true">
                    <u-radio v-for="(item, index) in info.shopMoneyRules" :key="index" :name="item.moneyRuleId">
                        {{ item.userMoneyRuleName }}
                    </u-radio>
                </u-radio-group>
            </view>

            <!-- 留言 -->
            <u-form-item label-width="auto" label-position="top" :border-bottom="false" label="付款留言：">
                <u-input style="background-color: #f7f5f5; " :height="200" :border="true" type="textarea"
                    v-model="orderData.remark" />
            </u-form-item>
        </view>

        <!-- 结算按钮 -->
        <u-button class="hy-btn" type="primary" ripple @click="toPayment">确认付款</u-button>
    </view>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue'
import { onLoad, onLaunch } from '@dcloudio/uni-app'

// 存储
import { storeToRefs } from 'pinia'
import { useConfigStore, useUserStore } from '@/store'

// API
import { moneyApi, orderApi, productApi,enumAll } from '@/api'

// 工具
import { getQueryVariable } from '@/utils/common'

// 图片资源
import moneyIcon from '@/static/hlhy/money2.png'
import shopIcon1 from '@/static/hlhy/shopIcon1.png'

// Props - 用于区分是哪种支付方式（积分规则）
const props = defineProps<{
    integralsRuleId: number // 1=花积分，4=复来券
}>()

// Pinia Store
const configStore = useConfigStore()
const userStore = useUserStore()
const {
    enterByStoreQrcode,
    isWeChatBrowser,
    isAlipayClient
} = storeToRefs(configStore)
const { accessToken, useShareCode } = storeToRefs(userStore)

// 数据状态
const info = reactive<any>({
    name: '',
    shopId: '',
    shopMoneyRules: []
})
const money = ref<string | null>(null)
const orderData = ref({
    remark: '',
    scoreMoney: 0,
    orderProductSkus: [] as any[]
})
const productSku = ref()
const flqScore = ref(0)
const moneyRuleId = ref(null)

// 积分相关状态
const score_consumption = ref(0)
const userScore = ref(0)
const maxUserScor = ref(0)
let _userScore = 0
const inptDisabled = ref(false)

// 计算最大可用积分
const scoreMax = computed(() => {
    if (!money.value || isNaN(parseFloat(money.value))) return 0
    const amount = parseFloat(money.value)

    let deductionRate = props.integralsRuleId === 1 ? 0.5 : flqScore.value
    let maxDeductible = amount * deductionRate

    return Math.min(maxDeductible, maxUserScor.value)
})

// 获取用户积分
async function getScore(walletRuleId: number) {
    const { data } = await moneyApi.walletInfo({ walletRuleId })
    userScore.value = Math.floor(data.money * 10) / 10
    maxUserScor.value = userScore.value
    _userScore = userScore.value
}

// 获取商品 SKU
async function getShopSku() {
    const { data } = await productApi.getShopProductSkuList({
        detail: false,
        dynamicPrice: true,
        shopId: info.shopId
    })

    if (data.records?.length) {
        productSku.value = data.records[0]
        orderData.value.orderProductSkus = [{
            count: 1,
            money: money.value,
            shopProductSkuId: productSku.value.id,
            moneyRuleId: moneyRuleId.value,
            dynamicPric: true
        }]
        if (score_consumption.value) {
            orderData.value.scoreMoney = score_consumption.value
        }
    }
}

// 创建订单
async function creatOrder() {
    try {
        const { data } = await orderApi.orderAdd(orderData.value)
        location.href = `https://api.mylkjgs.com/?token=${accessToken.value}&orderId=${data.id}`
    } catch (err) {
        console.error(err)
    }
    uni.hideLoading()
}

// 支付处理
async function toPayment() {
    if (!money.value || parseFloat(money.value) <= 0) {
        uni.showToast({ icon: 'none', title: '请输入有效金额' })
        return
    }

    if (score_consumption.value > scoreMax.value) {
        uni.showToast({ icon: 'none', title: '最多只能抵扣' + scoreMax.value + '元' })
        return
    }

    uni.showLoading({ title: '', mask: true })

    try {
        await getShopSku()
        if (uni.getStorageSync('shareCode') && useShareCode.value) {
            orderData.value.orderProductSkus[0].externalData = {
                userShareCode: uni.getStorageSync('shareCode')
            }
        }
        await creatOrder()
    } catch (err) {
        uni.hideLoading()
    }
}

// 获取店铺信息
async function getShopInfo() {
    const { data } = await productApi.getShopInfo({
        id: info.shopId,
        detail: true,
        otherColumns: 'moneyRuleDetails'
    })

    const { name, shopMoneyRules, code, user, integralsRuleId } = data
    uni.setStorageSync('shopCode', code)
    uni.setStorageSync('shopOwnerShareCode', user.shareCode)
    info.name = name

    if (integralsRuleId == props.integralsRuleId) {
        getScore(enumAll.wallet_rule_id_enum.花积分钱包)
        if (props.integralsRuleId === 4) {
            await getShopSku()
            flqScore.value = 0.5 // 示例值，实际应从接口获取
        }
    }

    if (shopMoneyRules?.length) {
        if (moneyRuleId.value) {
            const rule = shopMoneyRules.find(item => item.moneyRuleId == moneyRuleId.value)
            if (!rule) {
                info.shopMoneyRules = shopMoneyRules
                moneyRuleId.value = shopMoneyRules[0].moneyRuleId
            }
        } else {
            info.shopMoneyRules = shopMoneyRules
            moneyRuleId.value = shopMoneyRules[0].moneyRuleId
        }
    }
}

watch(accessToken, () => getShopInfo())

function radioGroupChange(e: any) {
    console.log(e)
}

defineExpose({
    money,
    score_consumption,
    scoreMax,
    userScore,
    // onScoreChange,
    toPayment
})
</script>

<style lang="scss" scoped>
.physicalShopCheck {
    padding: 30rpx;
    text-align: center;
    background: linear-gradient(#FAB791 0%, rgba(255, 250, 224, 0) 30%, );

    .topTitLe {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 20rpx;


        .leftTitle {
            text-align: left;
        }
    }

    .shopBox {
        // margin: 0 10rpx;
        padding: 20rpx;
        background: url('@/static/pay1.png') no-repeat;
        background-size: 100% 100%;
        box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1); // 外部阴影

        .name {

            text-align: center;
            margin-top: 20rpx;
            font-size: 32rpx;
            font-weight: bold;

        }
    }



    .inptBox {
        display: flex;
        justify-content: center;
        align-items: flex-end;
        padding: 20rpx 0;
        border-top: 1px solid #8080802e;
        border-bottom: 1px solid #8080802e;
        position: relative;
        margin-top: 40rpx;
        font-size: 50rpx;


        .unit {
            right: 0;
            top: 36rpx;
            font-size: 28rpx;
            margin-bottom: 10rpx;
        }
    }

    .yt-list-cell {
        display: flex;
        align-items: center;
        padding: 40rpx 0;
        position: relative;

        .cell-tit {
            flex: 1;
            font-size: 26rpx;
            color: #909399;
            text-align: left;

            .red {
                // color: #f92c1d;
                color: #ff6c18;
            }
        }

        &.shape2 {
            display: block;

            .cell-tip {
                display: flex;
                justify-content: space-between;
                margin-top: 20rpx;
                align-items: center;

                .wallet {
                    font-size: 28rpx;
                    color: #ff6c18;
                }
            }
        }
    }

    .radioBox {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-top: 40rpx;

        :deep(.u-radio) {
            justify-content: center;
        }
    }

    .hy-btn {
        margin-top: 50rpx;
    }
}

.inputBox {
    // border: none;
    // border-top: 1rpx solid #e1e1e1;
    // border-bottom: 1rpx solid #e1e1e1;
}
</style>
